import axios, { AxiosError, type Method } from 'axios'
import { useUserStore } from "../stores/index";
import router from "../router";
import { showToast } from "vant";
export const baseURL='https://consult-api.itheima.net/'
const instance = axios.create({
  //  1. 基础地址，超时时间
  baseURL,
  timeout:10000
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const store=useUserStore()
    if(store.user?.token && config.headers){
      config.headers.Authorization=`Bearer ${store.user.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // TODO 3. 处理业务失败
    if(res.data.code !==10000){
      showToast(res.data.message || '业务失败')
      return Promise.reject(res.data)
    }
    // TODO 4. 摘取核心响应数据
    return res.data
  },
  (err:AxiosError) => {
    // TODO 5. 处理401错误
    if(err.response?.status ===401){
      const store=useUserStore()
      store.delUser()
      router.push({
        path:'/login',
        query:{
          returnUrl:router.currentRoute.value.fullPath
        }
      })
    }
    return Promise.reject(err)
  }
)

export default instance
type Data<T>={
  code:string,
  message:string,
  data:T
}
export const request=<T>(
  url:string,
  method:Method='GET',
  submitData?:object
  )=>{
  return instance.request<any, Data<T>>({
    url,
    method,
    [method.toUpperCase()==='GET' ? 'params':'data']:submitData
  })
}
